﻿using System.Collections.Generic;
using Accona.Monitoring.AppStatistics;

namespace Accona.Monitoring.Publishers
{
    public class MemoryPublisher : IPublisher
    {
        private readonly Container _container = new Container();


        public void Publish(AppStatisticsEvent appStatisticsEvent)
        {
            var app = _container[appStatisticsEvent.Statistics.AppName];
            var nmspc = app[appStatisticsEvent.Statistics.StatNamespace];
            var tag = nmspc[appStatisticsEvent.Statistics.Tag];

            if (appStatisticsEvent.EventType == AppStatisticsEventType.Broadcast)
                tag.AppStatistics = appStatisticsEvent.Statistics;
            else if (appStatisticsEvent.EventType == AppStatisticsEventType.Increment)
            {
                if (tag.AppStatistics == null)
                    tag.AppStatistics = appStatisticsEvent.Statistics;
                else
                    tag.AppStatistics.Value += appStatisticsEvent.Statistics.Value;
            }
        }

        private abstract class MemoryPublisherTreeNode<T> where T : new()
        {
            private readonly Dictionary<string, T> _items =
                new Dictionary<string, T>();

            public T this[string appName]
            {
                get
                {
                    T app;
                    if (!_items.TryGetValue(appName, out app))
                    {
                        app = new T();
                        _items.Add(appName, app);
                    }
                    return app;
                }
            }

        }

        public IAppStatistics GetStatistics(string appName, string @namespace, string tagName)
        {
            var app = _container[appName];
            var nmspc = app[@namespace];
            var tag = nmspc[tagName];
            return tag.AppStatistics;
        }

        private class Container : MemoryPublisherTreeNode<App>
        {
            
        }

        private class App : MemoryPublisherTreeNode<Namespace>
        {
        
        }

        private class Namespace : MemoryPublisherTreeNode<Tag>
        {
            
        }

        private class Tag 
        {
            public IAppStatistics AppStatistics { get; set; }
        }

    }


}
